
import json

from rest_framework.generics import ListAPIView, UpdateAPIView, RetrieveAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from apps.headlines.models import Channel, Article, Comment
from apps.headlines.serializers import ChannelSerializer, ArticleChannelSerializer, ArticlesUserSeriazlizer, \
    ArticleSearchSerializer, ArticleDetailSerializer
from apps.headlines.utils import PageNum


# 频道列表

class ChannelAPIView(ListAPIView):
    queryset = Channel.objects.all()
    serializer_class = ChannelSerializer
    pagination_class = PageNum



# 文章列表

class ArticleChannelView(ListAPIView):
    serializer_class = ArticleChannelSerializer
    pagination_class = PageNum
    lookup_field = 'id'

    def get_queryset(self):
        id = self.kwargs['id']
        if id =='-1':
            return Article.objects.all().order_by('-comment_count')  # 降序排列
        else:
            return Article.objects.filter(channel_id=id)



# 根据关键字搜索文章
class SearchArticleView(ListAPIView):
    serializer_class = ArticleSearchSerializer
    pagination_class = PageNum
    def get_queryset(self):
        keyword = self.request.query_params.get('text')
        if keyword:
            return Article.objects.filter(content__contains=keyword)
        else:
            return Article.objects.all()


# 文章详情
class ArticleDetailView(RetrieveAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleDetailSerializer


# 收藏或者取消收藏功能
class CollectArticleView(RetrieveAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticlesUserSeriazlizer
    permission_classes = [IsAuthenticated]
    def put(self, request, id):
        article = Article.objects.get(id=id)
        article_users = article.collected_users.all()
        if request.user in article_users:
            article.collected_users.remove(request.user)
            article.save()
            return Response({'success': True, 'message': '取消收藏成功'})
        else:
            article.collected_users.add(request.user)
            article.save()
            return Response({'success': True, 'message': '收藏成功'})


# 评论文章
class CommentArticleView(CreateAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticlesUserSeriazlizer

    def post(self, request, id):
        user = request.user
        if user is not None or user.is_is_authenticated:
            data = json.loads(request.body.decode())
            content = data.get('content')
            parent = data.get('parent')
            try:
                article = Article.objects.get(id=id)
            except Exception as e:
                return None
            if parent:
                try:
                    comment = Comment.objects.get(article=article, id=int(parent))
                except Exception as e:
                    return None
                if article.comment_count:
                    article.comment_count += 1
                else:
                    article.comment_count = 0
                article.save()
                Comment.objects.create(user=request.user, content=content, article=article, parent=comment)
                return Response({"message": "新增评论成功", "success": "true"})
            else:
                try:
                    Comment.objects.create(user=request.user, content=content, article=article)
                except Exception as e:
                    return None
                if article.comment_count:
                    article.comment_count = article.comment_count
                else:
                    article.comment_count = 0
                article.comment_count += 1
                article.save()
                return Response({"message": "新增评论成功", "success": "true"})
        return Response({"errmsg": "error"})


# 发布文章
class PublishArticleView(CreateAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticlesUserSeriazlizer
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body.decode())
        labels = data.get('labels')
        image = data.get('image')

        from fdfs_client.client import Fdfs_client
        #     加载Fdfs的配置文件,来设置Tracker Server.
        client = Fdfs_client('shicifang/utils/fastdfs/client.conf')
        # 获取上传的图片对象
        # 读取二进制  read() 方法是读取图片的二进制数据
        image_data = image.read()
        # 上传图片
        result = client.upload_by_buffer(image_data)
        #     根据结果进行判断

        if result.get('Status') != 'Upload successed.':
            return Response({'msg': '请稍后再试'})
        file_id = result.get('Remote file_id')


        try:
            article=Article.objects.create(user=request.user,title=data['title'],content=data['content'],channel_id=data['channel'], image=file_id)
        except Exception as e:
            return None
        for label in labels:
            article.labels.add(label)
        return Response({"articleid": article.id,
                             "message": "发布成功",
                             "success": "true"}, status=201)








